package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.TooFarException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.SearchHttpUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.vo.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Value("${sky.shop.address}")
    private String  address;

    /**
     * 用户下单--最终目标：往数据库表中插入订单数据orders、订单明细数据order_detail
     *
     * @param dto
     */
    @Transactional  //0.开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        // 获取登录人id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        // 根据地址簿id获取地址簿信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        try {
            if(SearchHttpUtil.isFarDistance(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail(), address)){
                throw new TooFarException("超出配送范围");
//                System.out.println("超出配送范围"+"----------------------");
            }
        } catch (Exception e) {
            throw new TooFarException("超出配送范围");
        }

        // 查询购物车列表数据--条件：用户id
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> cartList = shoppingCartMapper.getBy(shoppingCart);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 1.构造订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        // 补充缺失的属性值
        orders.setNumber(System.currentTimeMillis()+"");    //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);           //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        orders.setUserId(userId);                           //下单人id
        orders.setOrderTime(LocalDateTime.now());           //下单时间
        orders.setPayStatus(Orders.UN_PAID);                //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());            //收货人手机号
        orders.setAddress(addressBook.getDetail());         //收货地址
        orders.setConsignee(addressBook.getConsignee());    //收货人
        orders.setUserName(user.getName());                 //下单人姓名

        // 2.插入订单数据到orders表中
        ordersMapper.insert(orders);
        log.info("订单id={}", orders.getId());

        // 3.构造订单明细列表数据--从购物车获取订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        cartList.forEach(cart->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });

        // 4.将订单明细列表数据批量插入到order_detail表中
        orderDetailMapper.insertBatch(orderDetailList);

        // 5.清空购物车数据（自己名下的）
        shoppingCartMapper.deleteByUserId(userId);

        // 6.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.getById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));
        //
        // return vo;

        // 模拟微信支付成功
        // 由于小程序id和商户id不匹配（或者没有商户id），导致微信支付不能正常返回数据，也就无法让微信平台回调该Java服务，那么订单状态需要手动修改
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    @Transactional
    public void oneMoreOrder(Long id) {
        //删除原本购物车
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);
        //从订单细节中获取菜品
        List<OrderDetail> details = ordersMapper.getByOrderId(id);
        //把菜品添加到购物车
        for (OrderDetail detail : details) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail,shoppingCart,"id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        ordersMapper.update(Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build());
    }
    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO,orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setPayStatus(Orders.PAID);
        orders.setId(id);
        ordersMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
//        修改订单状态
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(id);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(Orders.USERCANCELL);
        ordersMapper.update(orders);
    }

    /**
     * 订单搜索
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult searchOrders(OrdersPageQueryDTO dto) {
        //分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<OrderVO> vos = ordersMapper.getByPage(dto);
        //补充vos的订单菜品
        for (OrderVO vo : vos) {
            List<OrderDetail> details = orderDetailMapper.getByOrderId(vo.getId());
            List<String> dishes = details.stream().map(detail -> detail.getName()).collect(Collectors.toList());
            String dishesString = dishes.toString();
            vo.setOrderDishes(dishesString.substring(1,dishesString.length()-1));
        }
        return new PageResult(vos.getTotal(),vos.getResult());
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO countStatus() {
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        List<OrderCountVo> countVos = ordersMapper.countStatus();
        for (OrderCountVo countVo : countVos) {
            if(countVo.getStatus().equals(Orders.TO_BE_CONFIRMED)){
                statisticsVO.setToBeConfirmed(countVo.getCount());
            }else if(countVo.getStatus().equals(Orders.CONFIRMED)){
                statisticsVO.setConfirmed(countVo.getCount());
            }else if(countVo.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
                statisticsVO.setDeliveryInProgress(countVo.getCount());
            }
        }
        return statisticsVO;
    }

    /**
     * 取消订单
     *
     * @param dto
     */
    @Override
    public void cancelOrder(OrdersCancelDTO dto) {
        Orders orders = Orders.builder()
                .cancelReason(dto.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .id(dto.getId())
                .payStatus(Orders.REFUND)
                .build();
        ordersMapper.update(orders);
    }


    /**
     * 历史订单查询
     * @param dto
     * @return
     */
    @Override
    public PageResult historyOrdersPage(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<OrderVO> page=ordersMapper.page(dto);
        for (OrderVO orderVO : page) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
            if(orderVO.getStatus()==Orders.PENDING_PAYMENT) {
                LocalDateTime begin = orderVO.getOrderTime();
                LocalDateTime end = LocalDateTime.now();
                Duration between = Duration.between(begin, end);
                long minutes = between.toMinutes();
                if (minutes >= 15) {
                    orderVO.setStatus(Orders.CANCELLED);
                    orderVO.setCancelReason(Orders.TIMEOUT);
                    orderVO.setCancelTime(begin.plusMinutes(15));
                    ordersMapper.update(orderVO);
                }
            }
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
         Orders orders= ordersMapper.getById(dto.getId());
         if(orders==null){
             throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
         }
         else if(orders.getStatus() == Orders.TO_BE_CONFIRMED){
            orders.setStatus(Orders.CONFIRMED);
            ordersMapper.update(orders);

        }
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = ordersMapper.getById(id);
        List<OrderDetail> orderDetailList = ordersMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDetailList(orderDetailList);
        BeanUtils.copyProperties(orders,orderVO);
        return orderVO;
    }
}
